/**
 * ===========================================
 * Project: gamehistory-web
 * ===========================================
 * Package: com.cyou.gamehistory.front.web
 * 
 * Copyright (c) 2012, CYOU All Rights Reserved.
 * ===========================================
 */
package com.cyou.gamehistory.front.web;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cyou.annals.bean.GameInfo;
import com.cyou.annals.util.AnnalsClient;
import com.cyou.framework.pagination.proxy.PaginationSupport;
import com.cyou.framework.util.DateUtility;
import com.cyou.framework.util.StringUtility;
import com.cyou.gamehistory.entity.Game;
import com.cyou.gamehistory.entity.GameHistory;
import com.cyou.gamehistory.entity.UserInfo;
import com.cyou.gamehistory.service.AppInfoService;
import com.cyou.gamehistory.service.GameHistoryFeedService;
import com.cyou.gamehistory.service.GameHistoryService;
import com.cyou.gamehistory.service.GameService;
import com.cyou.gamehistory.service.UserInfoService;
import com.cyou.gamehistory.util.ApplicationConfig;
import com.cyou.gamehistory.util.ApplicationConstants;
import com.cyou.gamehistory.util.WebUtil;
import com.google.common.collect.Maps;

import freemarker.template.Configuration;

/**
 * <p>GameHistoryController</p>
 *
 * @since 1.0
 * @version 1.0 2012-12-4
 * @author zhangxingkai
 */
@Controller
@RequestMapping(value = "/f/gamehistory")
public class GameHistoryController {
	
	private static final Logger logger = LoggerFactory.getLogger(GameHistoryController.class);
	@Autowired
	private GameHistoryService gameHistoryService;
	@Autowired
	private GameService gameInfoService;
	@Autowired
	private GameHistoryFeedService gameHistoryFeedService;
	@Autowired
	private AppInfoService appInfoService;
	@Autowired
	private UserInfoService userInfoService;
	private static Map<Integer, Integer> gameYear = Maps.newLinkedHashMap();
	
	private static String requestUrl = ApplicationConfig.getValue("requestUrl");
	static {
		Integer year=DateUtility.now().getYear()+1900;
		for(int i=2001;i<=year;i++){
			gameYear.put(i, i);
		}
	}

	/**
	 * 第一次生成编年史
	 * @param session
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "edit")
	public String edit(HttpSession session,HttpServletRequest request,HttpServletResponse response, Model model ) {
		PaginationSupport<Game> gameInfoList = gameInfoService.getGamesByInitial(null, 1);
		UserInfo userinfo=userInfoService.getUserInfoByUserId(WebUtil.returnUserId(request, response));
		model.addAttribute("userinfo", userinfo);
		model.addAttribute("size", 1);
		model.addAttribute("gameYear", gameYear);
		model.addAttribute("gameInfoList", gameInfoList);
		UserInfo hisGameHistoryCloseFlag=(UserInfo) session.getAttribute("hisGameHistoryCloseFlag");
		if(hisGameHistoryCloseFlag!=null){
			model.addAttribute("hisSpace", hisGameHistoryCloseFlag);
		}
		return "/front/edit";
	}

	@RequestMapping(value = "save", method = RequestMethod.POST)
	public String save(Model model,HttpSession session ,HttpServletRequest request,HttpServletResponse response,String[] gameCode,String[] orderNum,String[] playBeginTime,String[] cost,String[] story) throws ServletException, IOException {
		
		
		UserInfo userinfo=userInfoService.getUserInfoByUserId(WebUtil.returnUserId(request, response));
		
		if(gameCode==null){
			return this.edit(session, request, response, model);
		}
		//判断是否第一次生成编年史
		List<GameHistory> gameHistoryList=gameHistoryService.getGameHistoryList(userinfo.getUserId());
		//如果为空或者size为0，是第一次生成，将更新appin表 使用次数字段
		if(gameHistoryList==null || (gameHistoryList!=null&&gameHistoryList.size()==0)){
			appInfoService.addUserCount();
		}else{
			appInfoService.addUseTimes();
		}
		
		//保存数据到gamehistory表中
		gameHistoryService.saveBatch(userinfo.getUserId(), gameCode, cost, orderNum, playBeginTime, story);
		
		
		Double totalCost=this.totalCost(cost);
		Integer beginYear=this.gameBeginAge(playBeginTime);
		Integer gameCount=orderNum.length;
		String honor=this.getHonor(orderNum.length);
		Integer storyCount=this.getStoryCount(story);
		//更新用户
		logger.info("用户更新  begin");
		UserInfo user=userInfoService.getUserInfoByUserId(userinfo.getUserId());
		String originalImageName=user.getGameHistoryImage();
		Integer year = Calendar.getInstance().get(Calendar.YEAR);
		Integer month = Calendar.getInstance().get(Calendar.MONTH) + 1;
		Integer day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
		String imageName = year + File.separator + month + File.separator + day + File.separator +String.valueOf(DateUtility.now().getTime())+"_"+String.valueOf(user.getUserId())+".jpg";
		user.setGameHistoryImage(imageName);
		user.setSmallImage(WebUtil.staticGetHeadshot(user.getPassport()));
		userInfoService.updateUserInfo(user,totalCost,beginYear,gameCount,honor,storyCount);
		
		//保存feed
		gameHistoryFeedService.saveGameHistoryFeed(userinfo,totalCost,beginYear,gameCount,honor);
		
		//更新userinfo表中    gamecount   costcount gamebegintime
		
		logger.info("用户更新  end  生成图片 begin");
		//生成图片
		Configuration config=new Configuration();
		config.setServletContextForTemplateLoading(session.getServletContext(), "/");
		try {
			gameHistoryService.createSpaceImage(config, user, userInfoService.userCount(),originalImageName);
		} catch (Throwable e) {
			logger.error("catch exception",e);
			e.printStackTrace();
		}
		logger.info("生成图片     end");
		request.getRequestDispatcher("/f/space").forward(request, response);
		return null;
	}
	/**
	 * 通过索引字母获取游戏列表
	 * @param pinyin
	 * @param tags
	 * @param pageNo
	 * @return
	 */
	@RequestMapping(value = "cgame")
	@ResponseBody
	public PaginationSupport<Game> gameList(String pinyin, String tags,Integer pageNo) {
		return gameInfoService.getGamesByInitial(pinyin, pageNo);
	}
	/**
	 * 后台 更新游戏数据 按钮
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "sgame")
	public void sgame(HttpServletResponse response) throws IOException {
		// TODO 需要修改状态
		boolean isDebug = false;
		logger.info("获取游戏数据begin    AnnalsClient.getGameList(isDebug)     begin");
		List<GameInfo> list = AnnalsClient.getGameList(isDebug);
		logger.info("获取游戏数据end    AnnalsClient.getGameList(isDebug)     end");
		logger.info("开始同步数据begin    gameService.saveGameInfoBatch(list);     begin");
		gameInfoService.saveGameInfoBatch(list);
		logger.info("同步数据end    gameService.saveGameInfoBatch(list);     end");
		response.getWriter().print("success");
	}
	/**
	 * 算出一共花费多少
	 * @param cost
	 * @return
	 */
	public Double totalCost(String[] cost){
		Double total=0d;
		for(int i=0;i<cost.length;i++){
			if(cost[i]!=null&&cost[i].trim()!=""){
				Double money=0d;
				try{
					money=Double.valueOf(cost[i]);
				}catch(Exception e){
					money=0d;
				}
				total+=money;
			}
		}
		return total;
	}
	/**
	 * 游戏开始年份
	 * @param playBeginTime
	 * @return
	 */
	public Integer gameBeginAge(String[] playBeginTime){
		Integer mix=Integer.valueOf(playBeginTime[0]);
		for(int i=0;i<playBeginTime.length;i++){
			Integer gameAge=Integer.valueOf(playBeginTime[i]);
			if(gameAge<mix){
				mix=gameAge;
			}
		}
		return mix;
	}
	/**
	 * 根据网游数量 算出称呼
	 * @param gameCount
	 * @return
	 */
	public String getHonor(Integer gameCount){
		if(gameCount<5){
			return "潜力级";
		}
		if(gameCount<10 && gameCount>=5){
			return "发烧级";
		}
		if(gameCount<15 && gameCount>=10){
			return "资深级";
		}
		if(gameCount<25 && gameCount>=15){
			return "骨灰级";
		}
		if(gameCount<30 && gameCount>=25){
			return "大神级";
		}
		if(gameCount<35 && gameCount>=30){
			return "超神级";
		}
		return "网游杀手";
		
	}
	public Integer getStoryCount(String[] story){
		Integer storyCount=0;
		if(story!=null&&story.length>0){
			for(String str:story){
				if(StringUtility.isNotBlank(str)){
					storyCount++;
				}
			}
		}
		return storyCount;
	}
	


}
